const sheetMixin = {
  data() {
    return {
      title: undefined,
      createTitle: undefined,
      updateTitle: undefined,
      openSheet: false,
      createFlag: true,
      formRef: undefined,
      originalForm: {},
      form: {},
      error: {},
      id: undefined,
      actionApi: {}
    }
  },
  computed: {
    isModified() {
      // 判断表单数据是否有变化
      return JSON.stringify(this.form) !== JSON.stringify(this.originalForm);
    }
  },
  methods: {
    /** 打开Dialog 画面 */
    openSheetDialog(data) {
      this.openSheet = !this.openSheet;
      this.reset();
      this.initialize()
      if (data) {
        this.title = this.updateTitle
        this.createFlag = false
        this.id = data.id
        this.form = data
      } else {
        this.title = this.createTitle
        this.createFlag = true
        this.id = undefined
      }
      this.originalForm = {
        ...this.form
      }
    },
    /** 初始化函数，在组件中重写并调用初始化用到的函数 */
    initialize() {},
    /** 在dialog关闭时判断当前form是否有修改 */
    cancel() {
      if (this.isModified) {
        this.$confirm(this.$t('leavingPrompt'), this.$t('info'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning',
          cancelButtonClass: 'btn-cancel-to-right'
        }).then(() => {
          this.openSheet = !this.openSheet
        }).catch(() => {
        });
      } else {
        this.openSheet = !this.openSheet
      }
    },
    reset() {
      this.resetForm(this.formRef)
      this.resetJsonObject(this.form)
      this.resetJsonObject(this.error)
    },
    /** 提交表单时，action需要指定更新类型 */
    submitForm(action, successMessage) {
      this.$refs[this.formRef].validate(async(valid) => {
        if (valid) {
          this.resetJsonObject(this.error)
          const api = this.actionApi[action]
          var resp;
          if (this.createFlag) {
            resp = await api(this.form);
          } else {
            resp = await api(this.id, this.form);
          }
          if (resp.success) {
            this.$emit('refreshList');
            this.openSheet = !this.openSheet
            this.targaMessage(successMessage);
          } else {
            if (typeof resp.msg === 'object') {
              this.error = resp.msg;
            } else {
              this.targaMessageBox(this, resp.msg);
            }
          }
        }
      });
    }
  }
}

export default sheetMixin
